package at.horario.service.impl;

import at.horario.model.HorarioSchedule;
import at.horario.service.HorarioScheduleManager;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class OptimizeJob implements Job {
    protected final Log log = LogFactory.getLog(getClass());
    private static final String APPLICATION_CONTEXT_KEY = "applicationContext";


    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            JobDataMap dataMap = context.getJobDetail().getJobDataMap();

            HorarioSchedule hs = (HorarioSchedule) dataMap.get("hs");
            ApplicationContext appCtx = getApplicationContext(context);

            HorarioScheduleManager horarioScheduleManager= (HorarioScheduleManager) appCtx.getBean("horarioScheduleManager");
            horarioScheduleManager.execute(hs);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }


    private ApplicationContext getApplicationContext(JobExecutionContext context )
    throws Exception {
        ApplicationContext appCtx = null;
        appCtx = (ApplicationContext)context.getScheduler().getContext().get(APPLICATION_CONTEXT_KEY);
        if (appCtx == null) {
            throw new JobExecutionException(
                    "No application context available in scheduler context for key \"" + APPLICATION_CONTEXT_KEY + "\"");
        }
        return appCtx;
    }
}
